<?php
//防止恶意调用
if (!defined('IN_TG')) exit('Access Defined!');

//跳转
function goUrl($url='1')
{
	if ($url=='1') {
		header('Location:'.$_SERVER['HTTP_REFERER']);
	} else {
		header('Location:'.$url);
	}
}

//json返回
function reAjax($info,$status=0,$url='')
{
	$data['info']=$info;
	$data['status']=$status;
	$data['url']=$url;
	ajaxReturn($data);
}

//Ajax方式返回数据
function ajaxReturn($data)
{
	header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($data));
}

//查看url中是否包含http
function ExecTime()
{
	$time = explode(" ", microtime());
	$usec = (double)$time[0];
	$sec = (double)$time[1];
	return $sec + $usec;
}

//密码加密
function pwdMd5($pwd){
	return md5(md5($pwd.'20130511'));
}

//清除HTML
function ClearHtml($str)
{
	$str = strip_tags($str);
	//首先去掉头尾空格
	$str = trim($str);
	//接着去掉两个空格以上的
	$str = preg_replace('/\s(?=\s)/', '', $str);
	//最后将非空格替换为一个空格
	$str = preg_replace('/[\n\r\t]/', ' ', $str);
	return $str;
}


//取IP
function getIP()
{
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		$cip = $_SERVER["HTTP_CLIENT_IP"];
	}else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}else if(!empty($_SERVER["REMOTE_ADDR"])){
		$cip = $_SERVER["REMOTE_ADDR"];
	}else{
		$cip = '';
	}
	preg_match("/[\d\.]{7,15}/", $cip, $cips);
	$cip = isset($cips[0]) ? $cips[0] : 'unknown';
	unset($cips);
	return $cip;
}

//截取指定长度的字符串
function ReStrLen($str, $len=10, $etc='...')
{
	$restr = '';
	$i = 0;
	$n = 0.0;

	//字符串的字节数
	$strlen = strlen($str);
	while(($n < $len) and ($i < $strlen))
	{
	   $temp_str = substr($str, $i, 1);

	   //得到字符串中第$i位字符的ASCII码
	   $ascnum = ord($temp_str);

	   //如果ASCII位高与252
	   if($ascnum >= 252)
	   {
			//根据UTF-8编码规范，将6个连续的字符计为单个字符
			$restr = $restr.substr($str, $i, 6);
			//实际Byte计为6
			$i = $i + 6;
			//字串长度计1
			$n++;
	   }
	   else if($ascnum >= 248)
	   {
			$restr = $restr.substr($str, $i, 5);
			$i = $i + 5;
			$n++;
	   }
	   else if($ascnum >= 240)
	   {
			$restr = $restr.substr($str, $i, 4);
			$i = $i + 4;
			$n++;
	   }
	   else if($ascnum >= 224)
	   {
			$restr = $restr.substr($str, $i, 3);
			$i = $i + 3 ;
			$n++;
	   }
	   else if ($ascnum >= 192)
	   {
			$restr = $restr.substr($str, $i, 2);
			$i = $i + 2;
			$n++;
	   }

	   //如果是大写字母 I除外
	   else if($ascnum>=65 and $ascnum<=90 and $ascnum!=73)
	   {
			$restr = $restr.substr($str, $i, 1);
			//实际的Byte数仍计1个
			$i = $i + 1;
			//但考虑整体美观，大写字母计成一个高位字符
			$n++;
	   }

	   //%,&,@,m,w 字符按1个字符宽
	   else if(!(array_search($ascnum, array(37, 38, 64, 109 ,119)) === FALSE))
	   {
			$restr = $restr.substr($str, $i, 1);
			//实际的Byte数仍计1个
			$i = $i + 1;
			//但考虑整体美观，这些字条计成一个高位字符
			$n++;
	   }

	   //其他情况下，包括小写字母和半角标点符号
	   else
	   {
			$restr = $restr.substr($str, $i, 1);
			//实际的Byte数计1个
			$i = $i + 1;
			//其余的小写字母和半角标点等与半个高位字符宽
			$n = $n + 0.5;
	   }
	}

	//超过长度时在尾处加上省略号
	if($i < $strlen)
	{
	   $restr = $restr.$etc;
	}

	return $restr;
}

//截断字符
function utf8_strcut($str, $start, $length=null) {   
	$str=str_replace("&nbsp;", "",$str);
	preg_match_all('/./us', $str, $match);   
	$chars = is_null($length)? array_slice($match[0], $start ) : array_slice($match[0], $start, $length);   
 
	unset($str);
 
 return implode('', $chars);   
} 

//类型列表  $url : ./list_{val}_2.html
function typeList($name,$dataArray,$url,$val){
	$rehtml='<dt>'.$name.'：</dt>';
	$newArray[0]='全部';
	foreach ($dataArray as $k => $v) {
		$newArray[$k]=$v;
	}
	foreach ($newArray as $k => $v) {
		$link_url=str_replace('{val}', $k, $url);
		$current=($val==$k)?'class="current"':'';
		$rehtml.='<dd><a href="'.$link_url.'" title="'.$v.'" '.$current.'>'.$v.'</a></dd>';
	}
	return $rehtml;
}

//在线客服
function onlinekefu(){
	if (DB_HOST=='localhost') return ;
	$thisfilename=strtolower(dirname($_SERVER['SCRIPT_NAME']));
	$kefu_code='<script>(function() {var _53code = document.createElement("script");_53code.src = "https://tb.53kf.com/code/code/9004029/1";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(_53code, s);})();</script>';
	if ($thisfilename!='/about' && $thisfilename!='/user' && $thisfilename!='/app' && $thisfilename!='/school' && $thisfilename!='/join'){
		return $kefu_code;
	}
}

//分页函数
function getPage($_sql,$_size=20,$count=0) {
	//将里面的所有变量取出来，外部可以访问
	global $_page,$_pagesize,$_pagenum,$_pageabsolute,$_num,$db;
	if (isset($_GET['page'])) {
		$_page = $_GET['page'];
		if (empty($_page) || $_page <= 0 || !is_numeric($_page)) {
			$_page = 1;
		} else {
			$_page = intval($_page);
		}
	} else {
		$_page = 1;
	}
	$_pagesize = $_size;
	//总记录数
	$_num=$count?$count:$db->getNumRows($_sql);

	if ($_num == 0) {
		$_pageabsolute = 1;
	} else {
		$_pageabsolute = ceil($_num / $_pagesize);
	}
	if ($_page > $_pageabsolute) {
		$_page = $_pageabsolute;
	}
	$_pagenum = ($_page - 1) * $_pagesize;
	return $_sql." LIMIT {$_pagenum},{$_pagesize}";
}

//判断是否是手机
function ismobile() {  
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备  
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))  
        return true;  
    //此条摘自TPM智能切换模板引擎，适合TPM开发  
    if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])  
        return true;  
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息  
    if (isset ($_SERVER['HTTP_VIA']))  
        //找不到为flase,否则为true  
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;  
    //判断手机发送的客户端标志,兼容性有待提高  
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {  
        $clientkeywords = array(  
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'  
        );  
        //从HTTP_USER_AGENT中查找手机浏览器的关键字  
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {  
            return true;  
        }  
    }  
    //协议法，因为有可能不准确，放到最后判断  
    if (isset ($_SERVER['HTTP_ACCEPT'])) {  
        // 如果只支持wml并且不支持html那一定是移动设备  
        // 如果支持wml和html但是wml在html之前则是移动设备  
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {  
            return true;  
        }  
    }  
    return false;  
}

//底部最新资讯
function footNews(){
	$cache_file=dirname(__FILE__).'/cache/footNews.cache';
	$cache_time=3600; //更新时间, 1小时

	if (!file_exists($cache_file) || time()>(filemtime($cache_file)+$cache_time)){
		global $db;
		$rehtml='';
		$slist=$db->getData("SELECT id,title FROM wb_info ORDER BY id DESC LIMIT 5");
		foreach ($slist as $v) {
			$rehtml.='<dd><a href="/info/content_'.$v['id'].'.html" title="'.$v['title'].'" target="_blank">'.$v['title'].'</a></dd>';
		}
		file_put_contents($cache_file,$rehtml);
	}else{
		$rehtml=file_get_contents($cache_file);
	}

	echo $rehtml;
}

//前版静态分页
function htmllistPages($url) {
	global $_page,$_pageabsolute,$_num;
	$pageNum=8;
	$rehtml='';
	
	if ($_pageabsolute==1) return '';//如果只有一页，则不显示分页
	if ($_page!=1){
		$rehtml.='<a href="'.$url.($_page-1).'.html">上一页</a> ';
	}
	if ($_page-$pageNum>0){
		$rehtml.='<a href="'.$url.'1.html">1 ...</a> ';
	}
	if ($_pageabsolute<$pageNum){//总记录小于显示
		for ($i=0;$i<$_pageabsolute;$i++) {
			if ($_page == ($i+1)) {
				$rehtml.='<span>'.($i+1).'</span>';
			} else {
				$rehtml.='<a href="'.$url.($i+1).'.html">'.($i+1).'</a>';
			}
		}
	}else{
		if ($_page<$pageNum){
			for ($i=0;$i<$pageNum;$i++) {
				if ($_page == ($i+1)) {
					$rehtml.='<span>'.($i+1).'</span>';
				} else {
					$rehtml.='<a href="'.$url.($i+1).'.html">'.($i+1).'</a>';
				}
			}
		}elseif($_page>$_pageabsolute-$pageNum+1){
			for ($i=$_pageabsolute-$pageNum;$i<$_pageabsolute;$i++) {
				if ($_page == ($i+1)) {
					$rehtml.='<span>'.($i+1).'</span>';
				} else {
					$rehtml.='<a href="'.$url.($i+1).'.html">'.($i+1).'</a>';
				}
			}
		}else{
			for ($i=$_page-$pageNum/2;$i<$_page+$pageNum/2;$i++) {
				if ($_page == ($i+1)) {
					$rehtml.='<span>'.($i+1).'</span>';
				} else {
					$rehtml.='<a href="'.$url.($i+1).'.html">'.($i+1).'</a>';
				}
			}
		}
	}
	if ($_pageabsolute-$_page>$pageNum-1){
		$rehtml.='<a href="'.$url.$_pageabsolute.'.html">... '.$_pageabsolute.'</a>';
	}
	if ($_page<$_pageabsolute){
		$rehtml.='<a href="'.$url.($_page+1).'.html" class="next">下一页</a>';
	}
	return $rehtml;
}
?>